<template>
  <div class="app-container">
    <el-form ref="opusForm" :model="opusForm" :rules="rules" label-width="120px">
      <!-- 标题 -->
      <el-form-item label="作品标题" prop="opusTitle">
        <el-input v-model="opusForm.opusTitle" placeholder="请输入作品标题" />
      </el-form-item>

      <!-- 封面图上传 -->
      <el-form-item label="作品封面" prop="opusCover">
        <el-upload
          style="border: 1px dashed #d9d9d9;"
          class="avatar-uploader"
          :action="uploadCoverUrl"
          :headers="uploadHeaders"
          :show-file-list="false"
          :on-success="handleCoverSuccess"
          :before-upload="beforeUpload"
        >
          <el-image
            v-if="opusForm.opusCover"
            :src="opusForm.opusCover"
            class="avatar"
          />
          <i v-else class="el-icon-plus avatar-uploader-icon" />
        </el-upload>
      </el-form-item>

      <el-form-item label="作品分类" prop="topicId">
        <el-select v-model="opusForm.topicId" placeholder="请选择分类">
          <el-option
            v-for="item in Options"
            :key="item.topicId"
            :label="item.topicName"
            :value="item.topicId"
          />
        </el-select>
      </el-form-item>

      <!-- 富文本编辑器 -->
      <el-form-item label="作品内容" prop="opusHtml">
        <vue-editor
          v-model="opusForm.opusHtml"
          :options="editorOption"
        />
      </el-form-item>

      <!-- 提交按钮 -->
      <el-form-item>
        <el-button type="primary" @click="handleSubmit">保存作品</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>

import { getToken } from '@/utils/auth' // 假设已实现 token 获取方法
import { VueEditor } from 'vue2-quill-editor'
import { getOptionList } from '@/api/topic'
import { createOrUpdateOpus, getOpusById } from '@/api/opus'

export default {
  name: 'OpusEditor',
  components: {
    VueEditor
  },
  data() {
    return {
      Options: [],
      opusForm: {
        opusId: null,
        opusTitle: '',
        opusCover: '',
        opusHtml: '<p>请输入作品内容...</p>',
        topicId: null,
        author: null,
        createTime: null
      },
      rules: {
        opusHtml: [
          { required: true, message: '内容不能为空', trigger: 'blur' }
        ]
      },
      uploadHeaders: {
        Authorization: `${getToken()}`
      },
      uploadCoverUrl: '/api/uploadfile/upload',
      editorOption: {
        modules: {
          toolbar: {
            container: [
              // 基础样式
              ['bold', 'italic', 'underline', 'strike'],
              // 标题和段落
              [{ 'header': '1' }, { 'header': '2' }, { 'header': 3 }, { 'header': 4 }, { 'header': false }],
              // 列表
              [{ 'list': 'ordered' }, { 'list': 'bullet' }],
              // 对齐方式
              [{ 'align': [] }, { 'align': 'center' }, { 'align': 'right' }, { 'align': 'justify' }],
              // 格式
              ['link', 'image', 'video', 'code-block', 'table'],
              // 颜色和背景
              [{ 'color': [] }, { 'background': [] }],
              // 缩进和方向
              [{ 'indent': '-1' }, { 'indent': '+1' }],
              [{ 'direction': 'rtl' }],
              // 清除格式
              ['clean']
            ],
            handlers: {
              image: this.quillImageHandler // 自定义图片上传
            }
          },
          // 启用图片缩放
          imageResize: {
            modules: ['ImageResize', 'ImageResizeHandle']
          }
        }
      }
    }
  },
  mounted() {
    const articleId = this.$route.params.id
    if (articleId != null && typeof articleId !== 'undefined' && articleId !== ':id') {
      getOpusById({ opusId: articleId }).then(res => {
        this.opusForm = res.opus
      })
    }
    getOptionList().then(res => {
      this.Options = res.topicList
    })
  },
  methods: {
    // 上传封面成功
    handleCoverSuccess(res) {
      console.log(res)
      this.opusForm.opusCover = res.url
    },
    // 上传前检查文件类型和大小
    beforeUpload(file) {
      const isImage = file.type.startsWith('image/')
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isImage) {
        this.$message.error('只能上传图片文件')
      }
      if (!isLt2M) {
        this.$message.error('图片大小不能超过 2MB')
      }
      return isImage && isLt2M
    },
    // 提交表单
    async handleSubmit() {
      await this.$refs['opusForm'].validate(async valid => {
        if (valid) {
          try {
            // 导出富文本内容为 HTML 字符串
            console.log(this.opusForm)
            await createOrUpdateOpus(this.opusForm)
            this.$message.success('作品保存成功')
            this.$router.push('/Main/index') // 跳转回列表页
          } catch (error) {
            console.log(error)
            this.$message.error('保存失败')
          }
        }
      })
    },
    // 重置表单
    resetForm() {
      this.$refs['opusForm'].resetFields()
      this.opusForm.opusHtml = '<p>请输入作品内容...</p>'
    }
  }
}
</script>

<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed darkgray;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

</style>
